package com.ruoyi.ruoyiqywechat.rediskey;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.qy.domain.User;
import com.ruoyi.ruoyiqywechat.domain.UserMembership;
import com.ruoyi.ruoyiqywechat.service.IUserMembershipService;
import com.ruoyi.ruoyiqywechat.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    private static final Logger logger = LoggerFactory.getLogger(RedisKeyExpirationListener.class);

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取过期的key
        String expiredKey = message.toString();
        logger.info("监听到key过期：{}", expiredKey);

        // 根据key的前缀进行不同的业务处理
        if (expiredKey.startsWith("member:")) {
            handleMemberExpired(expiredKey);
        }

        // 可以在这里添加更多的业务逻辑
    }
    @Autowired
    private UserService userService;

    @Autowired
    private IUserMembershipService userMembershipService;
    /**
     * 处理会员过期逻辑
     */
    private void handleMemberExpired(String key) {
        // 从key中提取订单ID
        String[] split = key.split(":");
        String userId = split[1];
        String memberPlanId = split[2];
        logger.info("会员过期处理，用户ID：{}  会员ID：{}", userId,memberPlanId);


        // 实际业务逻辑，比如：
        // 1. 修改用户会员状态
        User userServiceById = userService.getById(userId);
        userServiceById.setIsFenjian(false);
        userService.updateById(userServiceById);

        LambdaUpdateWrapper<UserMembership> userMembershipLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        userMembershipLambdaUpdateWrapper.eq(UserMembership::getUserId,userId).eq(UserMembership::getStatus,1)
                .set(UserMembership::getStatus,0);
        userMembershipService.update(userMembershipLambdaUpdateWrapper);
    }
    /**
     * 处理订单过期逻辑
     */
    private void handleOrderExpired(String key) {
        // 从key中提取订单ID
        String orderId = key.replace("order:", "");
        logger.info("订单过期处理，订单ID：{}", orderId);

        // 实际业务逻辑，比如：
        // 1. 更新订单状态为已过期
        // 2. 释放库存
        // 3. 发送通知等
    }

    /**
     * 处理会话过期逻辑
     */
    private void handleSessionExpired(String key) {
        String sessionId = key.replace("session:", "");
        logger.info("会话过期处理，会话ID：{}", sessionId);

        // 清理会话相关数据
    }

    /**
     * 处理缓存过期逻辑
     */
    private void handleCacheExpired(String key) {
        logger.info("缓存key过期：{}", key);
        // 可以执行一些缓存清理后的后续操作
    }
}
